using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class EnemyHealthBar : MonoBehaviour
{
    public GameObject owner;
    protected Damageable damageable;

    protected TextMeshProUGUI text;
    protected float curHealth;
    protected float maxHealth;

    public GameObject RenderBar;
    public Image FillImage;
    public Image CacheImage;

    protected Coroutine fillCoroutine = null;
    protected Coroutine cacheCoroutine = null;
    protected readonly float speed = 0.5f;

    protected virtual void Awake()
    {
        text = GetComponentInChildren<TextMeshProUGUI>();
    }

    protected virtual void OnEnable()
    {
        if (owner) UpdateBar();
    }
    protected void OnDisable()
    {
        if (fillCoroutine != null) StopCoroutine(fillCoroutine);
        if (cacheCoroutine != null) StopCoroutine(cacheCoroutine);
    }

    public virtual void Init(GameObject obj)
    {
        owner = obj;
        damageable = obj.GetComponent<Damageable>();
        UpdateBar();
    }

    public virtual void SetVisible(bool visible)
    {
        RenderBar.SetActive(visible);
    }

    public virtual void UpdateBar()
    {
        if (!gameObject.activeInHierarchy) return;

        curHealth = damageable.curHealth;
        maxHealth = damageable.Stats[STATS.maxHealth].Value();

        text.text = (int)curHealth + "/" + (int)maxHealth;

        if (fillCoroutine != null) StopCoroutine(fillCoroutine);
        fillCoroutine = StartCoroutine(UpdateFill(curHealth / maxHealth));

        if (cacheCoroutine != null) StopCoroutine(cacheCoroutine);
        cacheCoroutine = StartCoroutine(UpdateCache());
    }
    protected IEnumerator UpdateFill(float t)
    {
        while (FillImage.fillAmount != t)
        {
            FillImage.fillAmount = Mathf.MoveTowards(FillImage.fillAmount, t, Time.deltaTime * 1);
            yield return null;
        }
    }

    protected IEnumerator UpdateCache()
    {
        while (CacheImage.fillAmount != FillImage.fillAmount)
        {
            CacheImage.fillAmount = Mathf.MoveTowards(CacheImage.fillAmount, FillImage.fillAmount, Time.deltaTime * speed);
            yield return null;
        }
    }
}
